/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.gac.masai.getit;

import android.animation.Animator;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;

public class MainActivity extends Activity implements ActionBar.TabListener {
	// Use for DropBox login stuff

	//

	private View mActionBarView;
	private Animator mCurrentTitlesAnimator;
	private String[] mToggleLabels = { "Show Titles", "Hide Titles" };
	private int mLabelIndex = 1;
	private int mThemeId = -1;
	private Fragment mLastFragment;
	private Dialog mDialog;
	private final String DROPBOX_CRED = "DROPBOX_CRED"; // drop box credentials
	
	static Context mContext; //this is to access the context in PrefsFragment

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		Log.v("onNewIntent", intent.toString());
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);

			Log.v("SEARCH", query);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mContext = getApplicationContext();
		
		if (savedInstanceState != null
				&& savedInstanceState.getInt("theme", -1) != -1) {
			mThemeId = savedInstanceState.getInt("theme");
			this.setTheme(mThemeId);
			Log.d("MainActivity", "(onCreate)setThemeto : " + mThemeId);

		}
		Log.d("MainActivity", "mThemeID: " + mThemeId);
		setContentView(R.layout.main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		// Title Fragment
		// TitlesFragment titleFrag = (TitlesFragment) getFragmentManager()
		// .findFragmentById(R.id.frag_title);
		// titleFrag.selectPosition(1);
		// titleFrag.populateTitles();
		ActionBar bar = getActionBar();
		int i;
		String[] directory = new String[] { "Downloads", "Browser" };
		for (i = 0; i < directory.length; i++) {
			bar.addTab(bar.newTab().setText(directory[i]).setTabListener(this));
		}

		// bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.ad_action_bar_gradie));
		mActionBarView = getLayoutInflater().inflate(
				R.layout.action_bar_custom, null);

		bar.setCustomView(mActionBarView);
		bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
				| ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_SHOW_TITLE);
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		bar.setDisplayShowHomeEnabled(true);

		// Manually trigger onNewIntent to check for ACTION_DIALOG.
		onNewIntent(getIntent());
		Intent watcherStart = new Intent(this, DownloadWatcher.class);
		startService(watcherStart);

		/*
		 * Don't delete the two lines below. Otherwise an exception will occur
		 * when a new file is downloaded. It is not clear why this is the case.
		 * I suspect some issues with starting async tasks from services
		 */
		DropBox d = new DropBox();
		UploadAsync uplo = new UploadAsync(this, "/sdcard/Download/Cat2.jpg",
				"/GetIt", false);
		// uplo.execute(d);

		// If category is not saved to the savedInstanceState,
		// 0 is returned by default.
		if (savedInstanceState != null) {
			int category = savedInstanceState.getInt("category");
			bar.selectTab(bar.getTabAt(category));
		}
		FragmentManager fm = getFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		if(mLastFragment!=null && !(mLastFragment instanceof ContentFragment)){
			ft.replace(R.id.frag_content, mLastFragment);
		}else{
//			WelcomeFragment wf = new WelcomeFragment();
//			
//			ft.replace(R.id.frag_content, wf);
//			ft.commit();
		}
	}

	public void showToast(String msg) {
		Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
		toast.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		searchView.setIconifiedByDefault(false);
		// showDialog(0);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		FragmentManager fragmentManager = getFragmentManager();

		FragmentTransaction transaction = fragmentManager.beginTransaction();
		ContentFragment cf = new ContentFragment();
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case R.id.menu_search:
			onSearchRequested();
			return true;
		case R.id.toggleTheme:
			mLastFragment = fragmentManager.findFragmentById(R.id.frag_content);
			if (!(mLastFragment instanceof ContentFragment)){
				this.onBackPressed();
			}
			if (mThemeId == R.style.AppTheme_Dark) {
				mThemeId = R.style.AppTheme_Light;
				Log.d("MainActivity", "setThemetoLight : " + mThemeId);
			} else {
				mThemeId = R.style.AppTheme_Dark;
				Log.d("MainActivity", "setThemetoDark : " + mThemeId);
			}

			this.recreate();
			return true;
			/*
			 * //Commented this part out to see if it prevents the crashing case
			 * R.id.toggleTheme: if (mThemeId == R.style.AppTheme_Dark) {
			 * mThemeId = R.style.AppTheme_Light; } else { mThemeId =
			 * R.style.AppTheme_Dark; } this.recreate(); return true;
			 */

			// case R.id.showDialog:
			// showDialog("This is indeed an awesome dialog.");
			// return true;
			//
			// case R.id.showStandardNotification:
			// showNotification(false);
			// return true;
			//
			// case R.id.showCustomNotification:
			// showNotification(true);
			// return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("theme", mThemeId);
	}

	// @Override
	public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub

	}

	// @Override
	public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub

	}

	// @Override
	public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
		// TODO Auto-generated method stub

	}

}
